<?php
if ( ! defined('BASEPATH')) exit('No direct script access allowed');

/**
 * Feedback_service.php
 * 意见反馈逻辑
 * @author  :  Skiychan <dev@skiy.net>
 * @created :  2015/6/11
 * @modified:  
 * @version :  0.0.1
 */

class Feedback_service extends MY_Service {
    public $file_dir;  //上传的文件指定路径
    public $userinfo='';  //用户信息

    private $_title = '';
    private $_qq = '';
    private $_content = '';
    private $_email = '';
    private $_file_path = '';

    public function __construct() {
        parent::__construct();
        $this->file_dir = $this->config->item("default_upload_path").'feedback/images/';
    }

    /**
     * 上传文件
     * @param string $post_key 表单数据字段名
     * @return array|bool
     */
    public function upload($post_key="upload_file") {
        Common::create_folder($this->file_dir);
        $config['upload_path'] = $this->file_dir;
        $config['allowed_types'] = 'jpg|png|gif';
        $config['max_size'] = '2048';
        $config['file_name']  = Common::uniqid();
        $this->load->library('upload', $config);

        if(! $this->upload->do_upload($post_key)){
            return $this->set_error(1010, NULL, NULL, $this->upload->display_errors('',''));
        } else {
            $file_data = $this->upload->data();
            $res = array(
                'file_name' => $file_data['client_name'],
                'file_path' => $file_data['file_name']
            );
            return $res;
        }
    }

    /**
     * 发送邮件
     */
    private function send_email() {
        $contact = "<hr />";
        //添加登陆用户的信息
        if (! empty($this->userinfo))
            $contact .= implode('<br />', (array)$this->userinfo)."<br />";
        //联系方式
        if (! empty($this->_qq))
            $contact .= "QQ: ".$this->_qq."<br />";
        if (! empty($this->_email))
            $contact .= "Email: ".$this->_email."<br />";
        $contact .= "IP Address: ".$this->input->ip_address()."<br />";

        $user_email = empty($this->_email) ? $this->_qq.'@qq.com' : $this->_email;

        //加载CI的email类
        $this->load->library('email');
        //以下设置Email参数 已经在config/email.php
        //$this->email->initialize($config);

        $this->config->load("email");
        //以下设置Email参数 已经在config/email.php
        //$this->email->initialize($config);
        $from_email = $this->config->item('smtp_user');
        $to_email_arr = $this->config->item('receiver');
        $to_email = implode(',', $to_email_arr);

        //以下设置Email内容
        $this->email->from($from_email, '易控');
        //$this->email->from($user_email, '易控用户');
        //QQ邮箱或者直接邮箱
        $this->email->reply_to($user_email);
        $this->email->to($to_email);
        $this->email->subject($this->_title);
        $this->email->message($this->_content.$contact);

        $arr_files = array(); //临时文件数组
        if (! empty($this->_file_path)){
            $path_array = explode('|', $this->_file_path);
            foreach ($path_array as $v) {
                $this->email->attach($this->file_dir.$v);
            }
        }
        //发送成功
        if ($this->email->send()) {
            if ($this->config->item('feedback_file_delete')) {
                foreach ($arr_files as $v) {
                    unlink($this->file_dir.$v);
                }
            }
            return TRUE;
        }

        //设置发送失败
        $this->set_error(6001);
        return FALSE;
    }

    /**
     * @param $content 内容
     * @param string $contact 联系方式 数组形式要带键名,或单个字符串
     * @param string $title 标题
     * @param string $file_path 文件路径
     * @return bool
     */
    public function add($content, $contact='', $title='', $file_path='') {
        if (empty($content) || empty($contact)) {
            return $this->set_error(1003);
        }

        $this->_content = $content;
        $this->_title = empty($title) ? sprintf($this->lang->line('feedback'),date('Ymd')) : $title;
        $this->_file_path = $file_path;

        //取QQ和邮箱的信息
        if (is_array($contact)) {
            if (isset($contact['qq'])) $this->_qq = $contact['qq'];
            if (isset($contact['email'])) $this->_email = $contact['email'];
        } else {
            if ($this->form_validation->valid_email($contact)) {
                $this->_email = $contact;
            } else {
                $this->_qq = $contact;
            }
        }

        /* 这里是扩展，以后添加到数据库时需要用到 */
        $res = TRUE; //添加到数据库是否成功

        //添加到数据库成功
        if ($res) {
            //发送邮件
            return $this->send_email();
        } else {
            $this->set_error(1001);
            return FALSE;
        }
    }

    /**
     * 发送邮件
     * @param $content 内容
     * @param $contact 联系方式
     * @param $title 标题
     * @param $file_path 文件列表
     * @return bool 返回值
     * 2016.01.18 for android
     */
    public function doadd($content, $contact='', $title='', $file_path='') {
        if (empty($content))
            return $this->set_error(1003);

        //入数据库
        $resp = true;
       if (false == $resp)
          return $this->set_error(1001);

        return $this->dosend_email($content, $contact, $title, $file_path);
    }

    /**
     * 执行发送邮件操作
     * @param $content 内容
     * @param $contact 联系方式
     * @param $title 标题
     * @param $file_path 文件列表
     * @return bool 返回值
     * 2016.01.18 for android
     */
    private function dosend_email($content, $contact, $title, $file_path) {
        $footer = "<hr />";

        if (! empty($contact)) {
            foreach ($contact as $label => $value) {
                $footer .= $label.": ".$value."<br />";
            }
        }
        $footer .= "IP Address: ".$this->input->ip_address()."<br />";

        if (! empty($contact['email'])) {
            $user_email = $contact['email'];
        } else {
            if (! empty($contact['qq'])) {
                $user_email = $contact['qq']."@qq.com";
            } else {
                $user_email = (isset($contact['contact']) &&
                    $this->form_validation->valid_email($contact['contact'])) ?
                    $contact['contact'] : "guest@unclone.cn";
            }
        }

        $message = $content.$footer;

        //加载CI的email类
        $this->load->library('email');
        $this->config->load("email");
        //以下设置Email参数 已经在config/email.php

        $from_email = $this->config->item('smtp_user');
        $to_email_arr = $this->config->item('receiver');
        $to_email = implode(',', $to_email_arr);
        //$to_email = '1517005358@qq.com';

        //以下设置Email内容
        $this->email->from($from_email, '易控');  //SMTP 发送邮件
        $this->email->reply_to($user_email);  //回复接收者
        $this->email->to($to_email);  //接收反馈者
        $this->email->subject($title);  //标题
        $this->email->message($message);

        $file_arr = explode('|', $file_path);
        foreach ($file_arr as $file) {
            $this->email->attach($this->file_dir.$file);
        }

        //发送成功
        if ($this->email->send()) {
            //删除附件
            if ($this->config->item('feedback_file_delete')) {
                foreach ($file_arr as $file) {
                    unlink($this->file_dir.$file);
                }
            }
            return true;
        }

        //设置发送失败
        return $this->set_error(6001);
    }

    /**
     * 上传日志
     * @param string $post_key
     * @return array|bool
     */
    private function upload_log($post_key="error") {
        $this->file_dir = $this->config->item("default_upload_path").'feedback/logs/';
        Common::create_folder($this->file_dir);
        $config['upload_path'] = $this->file_dir;
        $config['allowed_types'] = 'txt|log';
        $config['max_size'] = '1024';
        $config['file_name'] = Common::uniqid(); //Common::uniqid();  //date("YmdHis_", time()).microtime()
        error_log(date("YmdHis_", time()).json_encode(microtime())."<>".Common::uniqid().PHP_EOL, 3, "logs/debug.txt");
        $this->load->library('upload', $config);

        if (!$this->upload->do_upload($post_key)) {
            $this->set_error(1010, NULL, NULL, $this->upload->display_errors('', ''));
            return FALSE;
        } else {
            $file_data = $this->upload->data();
            $res = array(
                'file_name' => $file_data['client_name'],
                'file_path' => $file_data['file_name']
            );
            return $res;
        }
    }
}